﻿//-----------------------------------------------------------------------------------
// <copyright file="AppDomainTestMethodInvokerTest.cs" company="P.O.S Informatique">
//     Copyright (c) P.O.S Informatique. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------------
namespace PosInformatique.DevelopmentTools.VisualStudio.TestExtensions.Tests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    using PosInformatique.Framework;

    [TestClass]
    public class AppDomainTestMethodInvokerTest
    {
        [TestMethod]
        public void InvokeTest()
        {
            Mock<TestMethodInvokerContext> context;
            context = new Mock<TestMethodInvokerContext>();
            context.SetupGet(c => c.TestMethodInfo)
                .Returns(typeof(TestClassWithMethod).GetMethod("MethodToInvoke"));

            AppDomainTestMethodInvoker invoker;
            invoker = new AppDomainTestMethodInvoker(context.Object);

            // Invoke the unit test method
            TestMethodInvokerResult result;
            result = invoker.Invoke();

            // Check the generated file
            string fileContent;
            fileContent = File.ReadAllText("AppDomainTestMethodInvokerTest.TestClassWithMethod.txt");

            Assert.AreEqual(
                "HasBeenInvoked-PosInformatique.DevelopmentTools.VisualStudio.TestExtensions.Tests.AppDomainTestMethodInvokerTest+TestClassWithMethod.MethodToInvoke()", 
                fileContent);

            // The static field "HasBeenInvoked" has set on the other AppDomain only... Check
            // if in the current AppDomain it has not been changed
            Assert.IsFalse(TestClassWithMethod.HasBeenInvoked);
        }

        private class TestClassWithMethod
        {
            public static bool HasBeenInvoked
            {
                get;
                private set;
            }

            public void MethodToInvoke()
            {
                if (File.Exists("AppDomainTestMethodInvokerTest.TestClassWithMethod.txt") == true)
                {
                    File.Delete("AppDomainTestMethodInvokerTest.TestClassWithMethod.txt");
                }

                File.AppendAllText(
                    "AppDomainTestMethodInvokerTest.TestClassWithMethod.txt",
                    "HasBeenInvoked-" + AppDomain.CurrentDomain.FriendlyName);

                // Set the has been initialized to true
                HasBeenInvoked = true;
            }
        }
    }
}
